/**
 * Copyright (c) 2013 An Yaming,  All Rights Reserved
 */
package so.shanku.essential.activity;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil.IGetServicesDataCallBack;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.UserDiscountAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车优惠券集合
 *
 * @author 马飞飞
 */
public class ShoppingRivilegeActivity extends BaseUIActivity {
	/**
	 * 无相关数据
	 */
	@ViewInject(id = R.id.nodata_layout)
	private LinearLayout nodata_layout;
	/**
	 * 显示购物车优惠券集合的列表
	 */
	@ViewInject(id = R.id.xlistview_discount, itemClick = "shoppingCartOnItemClick")
	private ListView xlistview_discount;
	/**
	 * 由购物车传入的订单商品信息 json格式
	 */
	private String selectProJson;
	/**
	 * 由购物车传入的订单商品信息
	 */
	private List<JsonMap<String, Object>> selectProduct;

	/**
	 * 购物车优惠券集合的数据
	 */
	private List<JsonMap<String, Object>> data_shopping_exchange_list;
	/**
	 * 购物车优惠券集合的数据适配器
	 */
	private UserDiscountAdapter userDiscountAdapter;

	/**
	 * 使用优惠券 返回订单页信息
	 */
	String ActualPayPrice = null;
	String coupon = null;
	String couponid = null;
	private String addressId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_discount);
		setCenter_title(R.string.my_coupon);
		Intent intent = getIntent();
		if (intent.getBooleanExtra(ExtraKeys.Key_Msg1, false)) {
			getData_Discount();
		} else {
			selectProJson = intent.getStringExtra(ExtraKeys.Key_Msg2);
			addressId = intent.getStringExtra(ExtraKeys.Key_Msg3);
			selectProduct = JsonParseHelper.getList_JsonMap(selectProJson);
			getData_getDefInfo();
		}

	}


	public void exchange_show(final String id) {
		Builder builder = new Builder(this);
		builder.setTitle(R.string.shopping_prompt);
		builder.setMessage(R.string.s_y_i_tv_confirm_youhuiquan);
		builder.setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		builder.setNegativeButton(R.string.ensure, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				loadingToast.show();
				Map<String, Object> params = new HashMap<String, Object>();
				params.put(GetDataQueue.Params_key,
						GetDataConfing.Key_shoppingUsedCoupon);
				params.put("userAccount", Utils.getUserAccount(mContext));
				params.put("ShoppingCartList", selectProduct);
				params.put("couponItemId", id);
				int addressIdInt = 0;
				try {
					addressIdInt = Integer.parseInt(addressId);
				} catch (Exception e) {
					e.printStackTrace();
				}
				params.put("addressId", addressIdInt);
				GetDataQueue queue = new GetDataQueue();
				queue.setActionName(GetDataConfing.Action_shoppingUsedCoupon);
				queue.setCallBack(callBack);
				queue.setParamsNoJson(params);
				queue.setWhat(what_tijiao);
				getDataUtil.getData(queue);
			}
		});
		builder.show();
	}

	/**
	 * 为优惠券集合添加适配器
	 */
	private void setAdatper_exchange_show(List<JsonMap<String, Object>> data) {
		this.data_shopping_exchange_list = data;
		userDiscountAdapter = new UserDiscountAdapter(this, data);
		xlistview_discount.setAdapter(userDiscountAdapter);
	}

	/**
	 * 个人中心优惠券展示添加适配器
	 *
	 * @param data
	 */
	private void setDiscount_show(List<JsonMap<String, Object>> data) {
		this.data_shopping_exchange_list = data;
		userDiscountAdapter = new UserDiscountAdapter(this, data);
		userDiscountAdapter.setDiscountflag(1);
		xlistview_discount.setAdapter(userDiscountAdapter);
		xlistview_discount.setClickable(false);
		xlistview_discount.setFocusable(false);

	}

	/**
	 * 获取填写信息的默认信息
	 */
	private void getData_getDefInfo() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key,
				GetDataConfing.Key_ShoppingUserCoupon);
		params.put("userAccount", Utils.getUserAccount(this));
		params.put("ShoppingCartList", selectProduct);

		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_ShoppingUserCoupon);
		queue.setCallBack(callBack);
		queue.setWhat(what_huoqujihe);
		queue.setParamsNoJson(params);

		getDataUtil.getData(queue);
	}

	public void getData_Discount() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key,
				GetDataConfing.Key_Str);
		params.put("UserName", Utils.getUserAccount(this));

		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_GetCouponItemVO);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.what_GetCouponItemVO);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}


	// 获取优惠券集合列表
	private final int what_huoqujihe = 1;
	private final int what_tijiao = 2;
	/**
	 * 调用服务器的回调
	 */
	private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {
				if (what_huoqujihe == entity.what) {
					setAdatper_exchange_show(JsonParseHelper
							.getJsonMap_List_JsonMap(entity.getInfo(),
									JsonKeys.Key_Info));
				} else if (what_tijiao == entity.what) {
					if (ShowGetDataError.isOkAndCodeIsNot1(mContext, entity.getInfo())) {
						List<JsonMap<String, Object>> info = JsonParseHelper
								.getJsonMap_List_JsonMap(entity.getInfo(),
										JsonKeys.Key_Info);
						if (info.size() > 0) {
							JsonMap<String, Object> data = info.get(0);
							if ("" != data.getStringNoNull("ActualPayPrice")) {
								ActualPayPrice = data.getStringNoNull("ActualPayPrice");
								coupon = data.getStringNoNull("CouponDiscountMoney");

								mContext.finish();
							}
						}

					}
				} else if (entity.what == GetDataConfing.what_GetCouponItemVO) {
					setDiscount_show(JsonParseHelper
							.getJsonMap_List_JsonMap(entity.getInfo(),
									JsonKeys.Key_Info));
				}

			} else {
				ShowGetDataError
						.showNetError(mContext);
			}
			loadingToast.dismiss();
			invalidateListData();
		}
	};

	private void invalidateListData() {
		if (data_shopping_exchange_list == null || data_shopping_exchange_list.size() < 1) {
			xlistview_discount.setVisibility(View.GONE);
			nodata_layout.setVisibility(View.INVISIBLE);
			toast.showToast(R.string.no_rivilege);
		} else {
			xlistview_discount.setVisibility(View.VISIBLE);
			nodata_layout.setVisibility(View.GONE);
		}
	}

	@Override
	public void finish() {
		Intent intent = getIntent();
		intent.putExtra(
				ExtraKeys.Key_Msg1, ActualPayPrice);
		intent.putExtra(
				ExtraKeys.Key_Msg2, coupon);
		intent.putExtra(
				ExtraKeys.Key_Msg3, couponid);
		setResult(RESULT_OK, intent);
		super.finish();
	}

	/**
	 * 购物车中的商品的的点击的事件处理
	 */
	public void shoppingCartOnItemClick(AdapterView<?> parent, View view,
	                                    int position, long id) {
		try {
			couponid = data_shopping_exchange_list.get(position)
					.getStringNoNull("Id");

			exchange_show(couponid);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
